package com.zjw.zy.heart.userpool;


import com.zjw.zy.heart.utils.LogUtils;
import jakarta.websocket.Session;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserPool implements IUserPool {

    private static final String TAG = "UserPool";
    private final Map<String, Session> pool = new ConcurrentHashMap<>();

    @Override
    public void connect(String username, Session session) {
        LogUtils.d(TAG, "connect user " + username);
        pool.put(username, session);
    }

    @Override
    public void disConnect(String username) {
        LogUtils.d(TAG, "disconnect user " + username);
        Session session = pool.remove(username);
        if (session != null && session.isOpen()) {
            try {
                session.close();
            } catch (IOException e) {
                LogUtils.e(TAG, "disConnect error", e);
            }
        }
    }

    @Override
    public Session querySession(String username) {
        LogUtils.d(TAG, "querySession user " + username);
        return pool.get(username);
    }

    @Override
    public void flush() {
        LogUtils.d(TAG, "flush start");
        for (Session session : pool.values()) {
            try {
                session.close();
            } catch (IOException e) {
                LogUtils.e(TAG, "flush error", e);
            }
        }
        pool.clear();
    }

    @Override
    public long getCount() {
        return pool.size();
    }
}
